<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" class="form-dialog">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <!--        <SvgIcon :icon="dialogIconMap[dialogMode]"/>-->
        <span>{{dialogTitle }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-row :gutter="12">
      <el-col :md="24">
        <el-card class="content-card">
          <el-tabs v-model="activeName">
            <el-tab-pane label="收款" name="first"></el-tab-pane>
            <el-tab-pane label="代付" name="second"></el-tab-pane>
          </el-tabs>
          <el-form ref="formRateRef" :disabled="readonly" :model="info" label-width="130px" v-if="activeName=='first'">
            <div class="mb-4">
              <el-checkbox-group disabled v-model="type" size="large" @change="handleChange">
                <div class="mb-3">
                  <el-checkbox v-for="item,index in cities" :label="item.name" :value="item.key" border />
                </div>
              </el-checkbox-group>
            </div>
            <div v-for="(item, index) in info.trade" :key="index">
              <div>{{item.name}}</div>
              <el-form-item :label="'费率(%)：'" :prop="'trade.' + index + '.rate'"
                            :rules="getValidationRules(index)">
                <el-input v-model="item.rate" :readonly="readonly" placeholder="请设置费率" />
              </el-form-item>
              <el-form-item :label="'单笔最小金额：'" :prop="'trade.' + index + '.min_amount'"
                            :rules="getValidationRules(index)">
                <el-input v-model="item.min_amount" :readonly="readonly" placeholder="请输入单笔最小金额" />
              </el-form-item>
              <el-form-item :label="'单笔最大金额：'" :prop="'trade.' + index + '.max_amount'"
                            :rules="getValidationRules(index)">
                <el-input v-model="item.max_amount" :readonly="readonly" placeholder="请输入单笔最大金额" />
              </el-form-item>
              <el-form-item :label="'单笔手续费：'" :prop="'trade.' + index + '.extra_charge'"
                            :rules="getValidationRules(index)">
                <el-input v-model="item.extra_charge" :readonly="readonly" placeholder="请输入单笔手续费" />
              </el-form-item>
              <el-form-item :label="'单笔最少手续费：'" :prop="'trade.' + index + '.min_charge'"
                            :rules="getValidationRules(index)">
                <el-input v-model="item.min_charge" :readonly="readonly" placeholder="请输入单笔最少手续费" />
              </el-form-item>
              <el-divider />
            </div>
          </el-form>
          <el-form ref="formRateRef" :disabled="readonly" :model="info" label-width="130px" v-else>
            <div class="mb-4">
              <el-checkbox-group v-model="types" size="large" @change="handleChangeDf">
                <div class="mb-3">
                  <el-checkbox disabled v-for="item,index in citiesDf" :label="item.name" :value="item.key" border />
                </div>
              </el-checkbox-group>
            </div>
            <div v-for="(item, index) in info.trans" :key="index">
              <div>{{item.name}}</div>
              <el-form-item :label="'费率(%)：'" :prop="'trans.' + index + '.rate'"
                            :rules="getValidationRules(index)">
                <el-input v-model="item.rate" :readonly="readonly" placeholder="请设置费率" />
              </el-form-item>
              <el-form-item :label="'单笔最小金额：'" :prop="'trans.' + index + '.min_amount'"
                            :rules="getValidationRules(index)">
                <el-input v-model="item.min_amount" :readonly="readonly" placeholder="请输入单笔最小金额" />
              </el-form-item>
              <el-form-item :label="'单笔最大金额：'" :prop="'trans.' + index + '.max_amount'"
                            :rules="getValidationRules(index)">
                <el-input v-model="item.max_amount" :readonly="readonly" placeholder="请输入单笔最大金额" />
              </el-form-item>
              <el-form-item :label="'单笔手续费：'" :prop="'trans.' + index + '.extra_charge'"
                            :rules="getValidationRules(index)">
                <el-input v-model="item.extra_charge" :readonly="readonly" placeholder="请输入单笔手续费" />
              </el-form-item>
              <el-form-item :label="'单笔最少手续费：'" :prop="'trans.' + index + '.min_charge'"
                            :rules="getValidationRules(index)">
                <el-input v-model="item.min_charge" :readonly="readonly" placeholder="请输入单笔最少手续费" />
              </el-form-item>
              <el-form-item :label="'手续费模式：'" :prop="'trans.' + index + '.fee_mode'"
                            :rules="getValidationRules(index)">
                <el-radio-group v-model="item.fee_mode">
                  <el-radio value="INNER" border>内扣</el-radio>
                  <el-radio value="PRIOR" border>预充值</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-divider />
            </div>
          </el-form>
        </el-card>
      </el-col>
    </el-row>


    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
<!--        <el-button  :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>-->
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import { SvgIcon } from '@/components/icon';
import useDialog from '@/hooks/use-dialog.ts';
import { StoreAlliance, storeAllianceInfo, StoreManager, storeAllianceSaveOrUpdate } from '@/api/api-store.ts';
import { StoreData } from '@/api/common.ts';
import { isImageUrl } from '@/utils/is.ts';
import { SelectRemote } from '@/components/other';
import {merchantEntryList} from "@/api/api-store.ts";
import {
  mccBigType,
  mccSmallType,
  cityTree, merchantInfo, merchantSave, merchantUpdate,
} from '@/api/api-store.ts';
defineOptions({name: 'store-alliance-form'})
const activeName=ref('first')
const info = ref<Object>({}); // Adjust type as necessary
const type = ref<string[]>([]);
const types = ref<string[]>([]);
const cities=ref([])
const citiesDf=ref([])
const formRef = ref<FormInstance>();
const formRateRef=ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);

/** 默认表单数据 */
const defaultForm: StoreAlliance = <StoreAlliance>{password: ""};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  password: [{required: true, message: '密码不能为空', trigger: 'blur'}],
});

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value;
})

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = computed(() => {
  return dialogMode.value == 1 || formData.value.id <= 0;
});
const key = ref<string[]>([]);
// const type = ref<string[]>([]);
/** 打开弹窗 */
const open = async (id) => {
  dialogTitle.value = '我的费率';
  dialogVisible.value = true;
  // 重置表单
  handleFormReset();
  handleProductList()
}
const handleProductList= async()=>{
  const config= await  merchantEntryList({action:'product'})
  cities.value=config.body.trade
  citiesDf.value=config.body.trans
  type.value=config.body.trade.map(item => item.key)
  const payee = config.body.trade.map(item => ({
    type: item.type,
    name:item.name,
    key:item.key,
    rate: item.info.rate,
    min_amount: item.info.min_amount,
    max_amount: item.info.max_amount,
    min_charge: item.info.min_charge,
    settle_mode: item.info.settle_mode, // 默认值
    extra_charge: item.info.extra_charge,
    limit_amount: item.info.limit_amount,
    site_name: item.support.site_name,
    site_url: item.support.site_url,
    screenshot_image: item.support.screenshot_image,
    tiny_app_id: item.support.tiny_app_id
  }));
  info.value.trade=payee;

  types.value=config.body.trans.map(item => item.key)
  const transDfs = config.body.trans.map(item => ({
    key: item.key,
    name:item.name,
    rate: item.info.rate,
    min_amount: item.info.min_amount,
    max_amount: item.info.max_amount,
    min_charge: item.info.min_charge,
    settle_mode: item.info.settle_mode, // 默认值
    extra_charge: item.info.extra_charge,
    limit_amount: item.info.limit_amount,
  }));
  // console.log(transDf)
  info.value.trans=transDfs;
}
// 提供 open 方法，用于打开弹窗
defineExpose({open});
const getValidationRules = (index: number) => {
  return [
    { required: true, message: '不能为空', trigger: 'blur' }
  ];
};
const handleChangeDf= () => {
  // 记录当前选中的类型
  const selectedTypes = new Set(types.value);
  // 确保 payee 是一个数组，然后更新 payee 列表，只保留选中的类型
  if (!info.value.trans) {
    info.value.trans = []; // 确保 payee 是一个数组
  }

  info.value.trans = info.value.trans.filter(item => selectedTypes.has(item.type));
  // 为新选中的类型添加条目
  types.value.forEach(selectedType => {
    // 检查当前类型是否已在 payee 中
    const exists = info.value.trans.some(item => item.type === selectedType);
    if (!exists) {
      info.value.trans.push({
        type: selectedType,
        rate: '',
        min_amount: '',
        max_amount: '',
        min_charge: '',
        extra_charge: '',
        fee_mode:''
      });
    }
  });
  console.log(info.value.trans)
};
// Handle change in checkbox group
const handleChange = () => {
  // 记录当前选中的类型
  const selectedTypes = new Set(type.value);
  // 确保 payee 是一个数组，然后更新 payee 列表，只保留选中的类型
  if (!info.value.trade) {
    info.value.trade = []; // 确保 payee 是一个数组
  }

  info.value.trade = info.value.trade.filter(item => selectedTypes.has(item.type));
  // 为新选中的类型添加条目
  type.value.forEach(selectedType => {
    // 检查当前类型是否已在 payee 中
    const exists = info.value.trade.some(item => item.type === selectedType);
    if (!exists) {
      info.value.trade.push({
        type: selectedType,
        rate: '',
        min_amount: '',
        max_amount: '',
        min_charge: '',
        extra_charge: ''
      });
    }
  });
  console.log(info.value.trade)
};
/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  try {
    const v1 = await formRef.value?.validate();
    const v2 = await formRateRef.value?.validate();
    console.log('验证结果:', v1, v2); // 调试验证结果
  }catch (error) {
    console.log('校验错误:', error); // 打印校验错误
    ElMessage({ type: 'error', message: '请检查是否有必填项未完善' });
  }

};

/** 重置表单 */
const handleFormReset = () => {
  // 重置表单数据
  formData.value = {...defaultForm};
  activeName.value='first'
  // 重置界面表单数据
  formRef.value?.resetFields();
}
</script>

<style lang="scss" scoped>
.form-dialog {
  .el-input-number {
    max-width: 13rem;
  }
}
</style>
